<template>
  <ElDrawer v-model="opened" :title="formType" size="50%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <ElFormItem label="村庄名称" :label-width="labelWidth" prop="villageName">
        <ElInput v-model="form.villageName" />
      </ElFormItem>
      <ElFormItem label="村庄类型" :label-width="labelWidth" prop="villageType">
        <el-select v-model="form.villageType" :clearable="true" :fit-input-width="true">
          <el-option v-for="item in VillageInfo.TypeEnum" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </ElFormItem>
      <ElFormItem label="所属行政村" :label-width="labelWidth" prop="parentId" v-if="form.villageType && form.villageType === 1">
        <el-select v-model="form.parentId" :clearable="true" :fit-input-width="true">
          <el-option v-for="item in parentDataList" :key="item.id" :label="item.villageName" :value="item.id" />
        </el-select>
      </ElFormItem>
      <el-row>
        <el-col :span="8">
          <ElFormItem label="户籍人口" :label-width="labelWidth" prop="registeredPopulation">
            <ElInputNumber v-model="form.registeredPopulation" />
          </ElFormItem>
        </el-col>
        <el-col :span="8">
          <ElFormItem label="常住人口" :label-width="labelWidth" prop="permanentPopulation">
            <ElInputNumber v-model="form.permanentPopulation" />
          </ElFormItem>
        </el-col>
        <el-col :span="8">
          <ElFormItem label="劳动力" :label-width="labelWidth" prop="labourForce">
            <ElInputNumber v-model="form.labourForce" />
          </ElFormItem>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <ElFormItem label="经度" :label-width="labelWidth" prop="longitude">
            <ElInput v-model="form.longitude" />
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="纬度" :label-width="labelWidth" prop="latitude">
            <ElInput v-model="form.latitude" />
          </ElFormItem>
        </el-col>
      </el-row>
      <ElFormItem label="简介" :label-width="labelWidth" prop="content">
        <Editor v-model:value="editorValue" :style="'height: ' + editorHeight + 'px'" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance } from 'element-plus'
import { FormType } from '@/enums'
import { VillageInfo, getVillageInfoDetail, saveOrUpdateVillageInfo, listVillageInfo } from '@api/tby/community/villageInfo'
import Editor from '@/components/WangEditor/index.vue'
import { ElMessage } from 'element-plus'
import { validateLatitude, validateLongitude, validateInteger } from '@/api/modules/tby/common/common'

const editorValue = ref('')
const labelWidth = 100
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<VillageInfo.Form>>({})
const parentDataList = ref<VillageInfo.Record[]>()
const editorHeight = ref(450)

onMounted(async () => {
  console.log('进来了')
  let divHeight: number = document.body.clientHeight
  editorHeight.value = divHeight - 420
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

const rules = reactive<FormRules>({
  villageName: [
    { required: true, message: '村庄名称不能为空', trigger: 'blur' },
    { max: 20, message: '设备名称最大20个字符', trigger: 'blur' }
  ],
  villageType: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
  registeredPopulation: [
    { required: true, message: '户籍人口不能为空', trigger: 'blur' },
    { validator: validateInteger, trigger: 'blur' }
  ],
  permanentPopulation: [
    { required: true, message: '常住人口不能为空', trigger: 'blur' },
    { validator: validateInteger, trigger: 'blur' }
  ],
  labourForce: [
    { required: true, message: '劳动力不能为空', trigger: 'blur' },
    { validator: validateInteger, trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { max: 32, message: '经度最大32个字符', trigger: 'blur' },
    { validator: validateLongitude, trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { max: 32, message: '纬度最大32个字符', trigger: 'blur' },
    { validator: validateLatitude, trigger: 'blur' }
  ]
})

const open = async (type: FormType, id?: number) => {
  form.value = {}
  formType.value = type
  editorValue.value = ''
  let query: VillageInfo.Query = { current: 1, size: 1000, villageType: 0 }
  const { data } = await listVillageInfo(query)
  parentDataList.value = data
  opened.value = true
  if (isAdd.value) {
    loading.value = false
  } else {
    try {
      const { data } = await getVillageInfoDetail(id!)
      loading.value = false
      form.value = data
      if (data.content) {
        editorValue.value = data.content
      }
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
  editorValue.value = ''
  form.value = {}
}

const onSaveClicked = () => {
  if (!formRef.value) {
    return
  }
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    if (editorValue.value == '') {
      ElMessage({
        type: 'error',
        message: '请输入简介!'
      })
      return
    }
    const formData = { ...unref(form) }
    formData.content = editorValue.value
    saveOrUpdateVillageInfo(formData).then(() => {
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
